# -*- coding: utf-8 -*-

from log import logger
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

__author__ = '欧晓东'


type_dict = {1: "plain", 2: "html"}
server_addr = "smtp.163.com"
server_port = 25
admin_account = "wxapp201707@163.com"
admin_pwd = "wxpub413414"
user_list = ["513384683@qq.com", "740187403@qq.com", "402843216@qq.com"]
# user_list = ["402843216@qq.com"]


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr))


def send_email(to_user=user_list, msg_type=1, message="hello! admin!"):
    msg = MIMEText(message, type_dict[msg_type], 'utf-8')
    msg['From'] = _format_addr(u"wxapp后台警报系统 <%s>" % admin_account)
    to = []
    for user in to_user:
        to.append(u'管理员 <%s>' % user)
    msg['To'] = _format_addr(u",".join(to))
    msg['Subject'] = Header(u"后台警报提醒！！！", 'utf-8').encode()
    try:
        server = smtplib.SMTP(server_addr, server_port)
        server.login(admin_account, admin_pwd)
        server.sendmail(admin_account, to_user, msg.as_string())
        logger.info(u"系统邮件发送成功！")
        server.quit()
    except smtplib.SMTPException as e:
        logger.info(u"系统邮件发送失败！ errMsg: %s" % str(e))
